package fun.coding.leetcode;

public class ReverseWordsInAString {

	public static void main(String[] args) {
		ReverseWordsInAString ins = new ReverseWordsInAString();
		//System.out.println(ins.reverseWords("the sky is blue"));
		System.out.println(ins.reverseWords(" "));
		System.out.println(ins.reverseWords("  a  b "));
	}
	
	public String reverseWords(String s) {
		if (s == null || s.isEmpty()) return "";
		
		s = s.trim();
		
		String[] words = s.split(" ");
		
		StringBuilder sb = new StringBuilder();
		
		for (int i = words.length - 1; i >= 0; i--) {
			if (words[i].trim().length() == 0) continue;
			
			sb.append(words[i].trim());
			if (i != 0) {
				sb.append(" ");
			}
		}
		return sb.toString();
	}

}
